package com.guqj.nio.netty.file;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.DefaultFileRegion;
import io.netty.channel.FileRegion;
import io.netty.channel.SimpleChannelInboundHandler;

import java.io.File;
import java.io.RandomAccessFile;

public class FileServerHandler extends SimpleChannelInboundHandler<Object> {

	private final static String CR = System.getProperty("line.separator");

	@Override
	protected void messageReceived(ChannelHandlerContext ctx, Object msg) throws Exception {
		if (msg == null) {
			throw new Exception("the file is null");
		}
		File f = new File(msg.toString());
		if (f.exists()) {
			if (!f.isFile()) {
				ctx.writeAndFlush("not a file :" + f + CR);
				return;
			}
			ctx.write(f + " " + f.length() + CR);
			RandomAccessFile randomAccessFile = new RandomAccessFile((String) msg, "r");
			FileRegion fileRegion = new DefaultFileRegion(randomAccessFile.getChannel(), 0, randomAccessFile.length());
			ctx.write(fileRegion);
			ctx.writeAndFlush(CR);
			randomAccessFile.close();
		} else {
			throw new Exception("the file is not found");
		}
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
		ctx.close();
	}

}
